<template>
    <div>
        <div class="p-4">
            <el-form :inline="true" :model="searchParams" class="demo-form-inline">
                <el-form-item label="关键字搜索">
                    <el-input v-model="searchParams.nameKeyword" placeholder="关键字" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="getList">搜索</el-button>
                </el-form-item>
            </el-form>
            <div class="mt-3">
                <el-button v-if="btnShow('002')" type="primary" icon="Plus" @click="add">新增</el-button>
                <!-- <el-button v-if="btnShow('007')" type="danger" icon="Delete" @click="bachRemove">删除</el-button> -->
            </div>
            <div class="mt-3">
                <el-table ref="tableRef" :data="data" fit border style="width: 100%" row-key="id"
                    @row-click="handleRowClick" @selection-change="handleSelectionChange"
                    :row-class-name="getTableRowClassName">
                    <el-table-column align="center" type="selection" width="55" />
                    <el-table-column align="center" type="index" :index="indexMethod" label="序号" width="60" />

                    <el-table-column align="center" fit label="角色名称" prop="roleName" sortable />

                    <!-- <el-table-column align="center" fit label="角色类型： 10.管理员 20.用户" prop="roleType" sortable /> -->

                    <el-table-column align="center" fit label="状态" prop="status">
                        <template #default="scope">
                            <el-tag v-if="scope.row.status == 1" type="primary" effect="light">启用</el-tag>
                            <el-tag v-else type="danger" effect="light">禁用</el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column align="center" fit label="创建时间" prop="createTime" sortable />

                    <el-table-column align="center" fit label="创建人" prop="createName" sortable />

                    <el-table-column align="center" fit label="修改时间" prop="updateTime" sortable />

                    <el-table-column align="center" fit label="修改人" prop="updateName" sortable />

                    <el-table-column fixed="right" fit align="center" label="操作">
                        <template #default="scope">
                            <!-- <el-button link type="danger" size="small" @click="setRight(scope.row)">菜单权限</el-button> -->
                            <el-button v-if="btnShow('003')" link type="primary" size="small"
                                @click="edit(scope.row)">编辑</el-button>
                            <el-button v-if="btnShow('006')" link type="danger" size="small"
                                @click="del(scope.row)">删除</el-button>
                            <el-button v-if="btnShow('004')" link type="primary" size="small"
                                @click="setRight(scope.row)">菜单权限</el-button>
                            <el-button v-if="btnShow('005')" link type="primary" size="small"
                                @click="setDataRight(scope.row)">数据权限</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="mt-3">
                <el-pagination v-model:current-page="searchParams.pageNumber" v-model:page-size="searchParams.pageSize"
                    :page-sizes="[10, 20, 30, 50]" :background="background"
                    layout="total, sizes, prev, pager, next, jumper" :total="totalRow" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </div>

        <!-- 添加与编辑 -->
        <el-dialog v-model="addDialog" :title="isAdd ? '添加' : '编辑'" width="60%" center>

            <!-- 编辑表单信息 -->
            <el-form label-width="auto" ref="editItemRef" :model="editItem" :rules="editItemRules" class="demo-ruleForm"
                status-icon>


                <el-form-item label="角色名称" prop="roleName">
                    <el-input placeholder="请输入角色名称" v-model="editItem.roleName"></el-input>
                </el-form-item>

                <!-- <el-form-item label="角色类型： 10.管理员 20.用户" prop="roleType">
                    <el-input placeholder="请输入角色类型： 10.管理员 20.用户" v-model="editItem.roleType"></el-input>
                </el-form-item> -->
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="addDialog = false">取消</el-button>
                    <el-button type="primary" @click="save(editItemRef)">保存</el-button>
                </div>
            </template>
        </el-dialog>


        <!-- 操作提示弹框 -->
        <el-dialog v-model="openDialog" title="操作提示" width="40%" center>
            <span class="m-t-10 m-b-10">{{ openDialogTitle }}</span>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="openDialog = false">取消</el-button>
                    <el-button type="primary" @click="confirm">确认</el-button>
                </div>
            </template>
        </el-dialog>


        <!-- 设置菜单权限 -->
        <el-dialog v-model="isSetRight" :title="editRight.roleName + `  设置菜单权限`" width="50%">
            <el-tree ref="treeRef" :height="208" :data="menus" show-checkbox node-key="id"
                :default-checked-keys="checkedKeys" :props="props" />
            <!-- :default-checked-keys="checkedKeys" -->

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="isSetRight = false">取消</el-button>
                    <el-button type="primary" @click="saveRoleRight">提交</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 设置数据权限 -->
        <el-dialog v-model="isSetDataRight" :title="dataRight.roleName + `  设置数据权限`" width="70%">

            <el-tree style="max-width: 600px" :data="dataSource" node-key="id" default-expand-all
                :expand-on-click-node="false" :props="props">
                <template #default="{ data }">
                    <span class="custom-tree-node">
                        <span v-if="data.menuType == 2">
                            <span v-if="data.kind == 1">{{ data.title + `(全部数据)` }}</span>
                            <span v-else-if="data.kind == 2">{{ data.title + `(部门数据)` }}</span>
                            <span v-else-if="data.kind == 3">{{ data.title + `(个人数据)` }}</span>
                            <span v-else>{{ data.title + `(无权限)` }}</span>
                        </span>
                        <span v-else>{{ data.title }}</span>
                        <span v-if="data.menuType == 2" style="margin-left: 20px;">
                            <a style="color: cornflowerblue;margin-left: 10px;" @click="addRoleData(data.id, 1)"> 全部权限
                            </a>
                            <a style="color: cornflowerblue;margin-left: 10px;" @click="addRoleData(data.id, 2)"> 部门权限
                            </a>
                            <a style="color: cornflowerblue;margin-left: 10px;" @click="addRoleData(data.id, 3)"> 个人权限
                            </a>
                            <a style="color: cornflowerblue;margin-left: 10px;" @click="addRoleData(data.id, 0)"> 无权限
                            </a>
                        </span>
                    </span>
                </template>
            </el-tree>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="isSetDataRight = false">关闭</el-button>
                    <!-- <el-button type="primary" @click="saveRoleRight" >提交</el-button> -->
                </span>
            </template>
        </el-dialog>
    </div>
</template>


<script setup>
import { indexMethod } from '@/config/utils';
import { ref } from 'vue';
import { getBtnList, getRoleList, delRole, delRoleByBach, checkRoleName, saveRole, getMenus, getRoleMenuIds, setRoleRight, setRoleDataRight, getRoleMenus, getRoleDataRight } from '@/config/api.js'
//获取当前路由信息
import { useRoute } from 'vue-router';
const route = useRoute();

//获取按钮权限
const btns = ref([])
const getBtns = () => {
    let data = {
        path: route.path
    }
    getBtnList(data).then(res => {
        btns.value = res.data
    })
}
getBtns();
const btnShow = (codeNo) => {
    let flag = btns.value.includes(codeNo);
    return flag
}

//搜索条件
const totalRow = ref(0)
const searchParams = ref({
    pageNumber: 1,
    pageSize: 10
})

//表格数据
const tableRef = ref()
const data = ref([])

//选择的行
const selectedRow = ref({})
//单击行
const handleRowClick = (row) => {
    // console.log('row ==> {}', row);
    selectedRow.value = row
    tableRef.value.clearSelection()
    tableRef.value.toggleRowSelection(row)
}
//设置行样式
const getTableRowClassName = ({ row }) => {
    if (row.id === selectedRow.value.id) {
        return 'tableRowStyle'
    }
    return ''
}
//获取列表数据
function getList() {
    //执行查询数据
    getRoleList(searchParams.value).then(res => {
        if (res.code == 200) {
            data.value = res.data.records
            totalRow.value = res.data.totalRow
        }
    })
}

//分页参数处理
const handleSizeChange = (e) => {
    searchParams.value.pageSize = e
    getList()
}
const handleCurrentChange = (e) => {
    searchParams.value.pageNumber = e
    getList()
}
getList();

//校验规则
const checkName = (rule, value, callback) => {
    if (!value || value === '') {
        callback(new Error('部门名称必填'))
    } else {
        //kind: 1.系统管理员添加店铺主账号 2.店铺自主注册 3.店铺添加员工
        let data = {
            deptName: value,
            id: editItem.value.id
        }
        checkRoleName(data).then(res => {
            if (res.code == 200) {
                callback()
            }
            else {
                callback(new Error(res.msg))
            }
        })
    }
}

//添加与编辑
const editItem = ref({})
const addDialog = ref(false)
const editItemRef = ref()

//表单校验
const editItemRules = ref({
    deptName: [
        { required: true, message: '角色名称必填', trigger: 'blur' },
        { validator: checkName, trigger: 'blur' }
    ],
})

//打开操作页面
const isAdd = ref(true)

//添加
const add = async () => {
    editItem.value = {}
    addDialog.value = true
}
//编辑
const edit = async (item) => {
    addDialog.value = true
    editItem.value = item
}

//保存信息
const save = (itemRef) => {
    if (!itemRef) return
    itemRef.validate((valid) => {
        if (valid) {
            // ElMessage.success('添加成功')
            saveRole(editItem.value).then(res => {
                if (res.code == 200) {
                    addDialog.value = false
                    ElMessage.success(res.msg)
                    getList();
                }
            })
        } else {
            ElMessage.error('表单校验未通过')
        }
    })
}



//删除
const openKind = ref({})
const openDialog = ref(false)
const openDialogTitle = ref('')
const openItem = ref({})
//单条删除
const del = (item) => {
    openDialog.value = true
    openKind.value = 1
    openDialogTitle.value = "确认要删除：" + item.roleName + " ?"
    openItem.value = item
}
//批量删除
const bachRemove = () => {
    const list = tableRef.value.getSelectionRows();
    console.log('选中的数据 ==> {}', list);
    if (list.length <= 0) {
        ElMessage.error('请先选择要操作的数据')
        return
    }
    openDialog.value = true
    openKind.value = 2
    openDialogTitle.value = "确认要删除选中的行？"
}

//提交确认信息
const confirm = () => {
    if (openKind.value == 1) {
        console.log('删除了 ==> {}', openItem.value.id);
        delRole(openItem.value).then(res => {
            if (res.code == 200) {
                openDialog.value = false
                ElMessage.success(res.msg)
                getList();
            }
            else {
                ElMessage.error(res.msg)
            }
        })
    }
    else if (openKind.value == 2) {
        const list = tableRef.value.getSelectionRows();
        const ids = list.map(item => item.id);
        // const names = list.map(item => item.roleName);
        // console.log('执行批量删除 ==> {}', ids);
        // console.log('执行批量删除 ==> {}', names);
        let data = {
            ids: ids
        }
        delRoleByBach(data).then(res => {
            if (res.code == 200) {
                openDialog.value = false
                ElMessage.success(res.msg)
                getList();
            }
            else {
                ElMessage.error(res.msg)
            }
        })
    }
    openDialog.value = false
}


// 设置角色权限
const menus = ref({})
const props = {
    value: 'id',
    label: 'title',
    children: 'children',
}
const isSetRight = ref(false)
const editRight = ref({})
const treeRef = ref(null);
const checkedKeys = ref([])
const setRight = (item) => {
    isSetRight.value = true
    editRight.value = item
    const data = {
        kind: 0
    }
    getMenus(data).then(res => {
        if (res.code == 200) {
            menus.value = res.data
        }
    })
    const dd = {
        roleId: item.id
    }
    getRoleMenuIds(dd).then(res => {
        if (res.code == 200) {
            checkedKeys.value = res.data
        }
    })

}
const saveRoleRight = () => {
    const checkedKeys = ref([]);
    checkedKeys.value = treeRef.value.getCheckedKeys();
    // console.log('选中的节点 ==> {}', checkedKeys.value);
    const data = {
        rellId: editRight.value.id,
        menuIds: checkedKeys.value
    }
    setRoleRight(data).then(res => {
        if (res.code == 200) {
            getList()
            getBtns();
            ElMessage.success(res.msg)
            isSetRight.value = false
        }
        else {
            ElMessage.error(res.msg)
        }
    })
}


// 设置角色的数据权限
const dataSource = ref({}) //角色的所有菜单
const isSetDataRight = ref(false)
const dataRight = ref([]) //
const setDataRight = (item) => {
    dataRight.value.roleId = item.id
    dataRight.value.roleName = item.roleName
    isSetDataRight.value = true
    getData(item.id);
}
const getData = (id) => {
    let data = {
        roleId: id
    }
    getRoleMenus(data).then(res => {
        if (res.code == 200) {
            dataSource.value = res.data
        }
    })
}
const addRoleData = (menuId, kind) => {
    const data = {
        roleId: dataRight.value.roleId,
        menuId: menuId,
        kind: kind
    }
    setRoleDataRight(data).then(res => {
        if (res.code == 200) {
            ElMessage.success(res.msg)
            getData(dataRight.value.roleId);
        }
        else {
            ElMessage.error(res.msg)
        }
    })
}

</script>

<style scoped></style>